import random
import datetime

# 商品数据
products = [
    {"id": 1, "name": "苹果", "price": 5.0, "stock": 10, "category": "水果"},
    {"id": 2, "name": "香蕉", "price": 3.0, "stock": 15, "category": "水果"},
    {"id": 3, "name": "牛奶", "price": 8.0, "stock": 8, "category": "饮品"},
    {"id": 4, "name": "面包", "price": 6.0, "stock": 12, "category": "食品"},
    {"id": 5, "name": "空调", "price": 3000.0, "stock": 5, "category": "家电"},
    {"id": 6, "name": "电视", "price": 5000.0, "stock": 3, "category": "家电"},
    {"id": 7, "name": "洗衣机", "price": 2500.0, "stock": 4, "category": "家电"}
]

# 购物车
shopping_cart = []

# 用户资金
money = 10000.0  # 增加初始资金以适应家电价格

# 优惠券系统
coupons = [
    {"type": "discount", "product_name": "空调", "discount": 0.8, "description": "空调8折优惠券"},
    {"type": "discount", "product_name": "电视", "discount": 0.85, "description": "电视85折优惠券"},
    {"type": "general", "discount": 0.95, "description": "全场95折优惠券"},
    {"type": "general", "discount": 0.9, "description": "全场9折优惠券"},
    {"type": "voucher", "amount": 50, "description": "50元抵用券"}
]

user_coupon = None


def draw_coupon():
    """随机抽取优惠券"""
    global user_coupon
    coupon = random.choice(coupons)
    user_coupon = coupon
    print("\n🎉 恭喜您抽到优惠券！")
    print(f"📜 优惠券: {coupon['description']}")
    return coupon


def apply_coupon(product_name, original_price):
    """应用优惠券计算折扣价格"""
    if not user_coupon:
        return original_price

    coupon = user_coupon

    if coupon['type'] == 'discount' and coupon['product_name'] == product_name:
        return original_price * coupon['discount']
    elif coupon['type'] == 'general':
        return original_price * coupon['discount']
    else:
        return original_price


def display_products():
    """显示所有商品"""
    print("\n" + "=" * 50)
    print("                    商品列表")
    print("=" * 50)
    print("ID\t商品名\t价格\t库存\t类别")
    print("-" * 50)
    for product in products:
        # 显示折扣价格（如果有优惠券）
        final_price = apply_coupon(product['name'], product['price'])
        price_display = f"{final_price:.1f}元"
        if final_price < product['price']:
            price_display += f" (原价:{product['price']}元)"

        print(f"{product['id']}\t{product['name']}\t{price_display}\t{product['stock']}\t{product['category']}")


def find_product(product_id):
    """根据ID查找商品"""
    for product in products:
        if product['id'] == product_id:
            return product
    return None


def find_cart_item(product_name):
    """在购物车中查找商品"""
    for item in shopping_cart:
        if item['name'] == product_name:
            return item
    return None


def add_to_cart(product, quantity):
    """添加到购物车"""
    global money

    # 检查库存
    if product['stock'] < quantity:
        print(f"❌ 库存不足！该商品只剩 {product['stock']} 个")
        return False

    # 计算折扣价格
    final_price = apply_coupon(product['name'], product['price'])
    total_price = final_price * quantity

    # 检查余额
    if money < total_price:
        print(f"❌ 余额不足！需要 {total_price:.2f}元，您只有 {money:.2f}元")
        return False

    # 检查购物车中是否已有该商品
    cart_item = find_cart_item(product['name'])
    if cart_item:
        # 如果已有，更新数量
        cart_item['quantity'] += quantity
        cart_item['total'] += total_price
    else:
        # 如果没有，添加到购物车
        shopping_cart.append({
            'name': product['name'],
            'price': product['price'],
            'final_price': final_price,
            'quantity': quantity,
            'total': total_price,
            'original_total': product['price'] * quantity
        })

    # 更新库存
    product['stock'] -= quantity
    # 扣款 - 这里修复了余额更新的问题
    money -= total_price

    print(f"✅ 购买成功！{product['name']} x{quantity}，花费 {total_price:.2f}元")
    if final_price < product['price']:
        print(f"   💰 优惠节省: {product['price'] * quantity - total_price:.2f}元")
    print(f"💰 您的余额还剩: {money:.2f}元")
    return True


def return_product():
    """退货功能"""
    global money  # 添加全局声明

    if not shopping_cart:
        print("❌ 购物车为空，无法退货！")
        return False

    print("\n🛒 当前购物车商品:")
    for i, item in enumerate(shopping_cart, 1):
        print(f"{i}. {item['name']} x{item['quantity']} - {item['total']:.2f}元")

    try:
        choice = int(input("\n请输入要退货的商品编号: ")) - 1
        if choice < 0 or choice >= len(shopping_cart):
            print("❌ 无效的商品编号！")
            return False

        item_to_return = shopping_cart[choice]
        return_quantity = int(input(f"请输入退货数量 (最大 {item_to_return['quantity']}): "))

        if return_quantity <= 0 or return_quantity > item_to_return['quantity']:
            print("❌ 无效的退货数量！")
            return False

        # 查找原商品
        original_product = None
        for product in products:
            if product['name'] == item_to_return['name']:
                original_product = product
                break

        if not original_product:
            print("❌ 找不到对应的商品！")
            return False

        # 计算退款金额（按实际支付价格退款）
        unit_refund = item_to_return['total'] / item_to_return['quantity']
        refund_amount = unit_refund * return_quantity

        # 更新库存
        original_product['stock'] += return_quantity

        # 更新购物车
        if return_quantity == item_to_return['quantity']:
            # 全部退货，移除商品
            shopping_cart.pop(choice)
        else:
            # 部分退货，更新数量
            item_to_return['quantity'] -= return_quantity
            item_to_return['total'] -= refund_amount

        # 退款 - 这里修复了余额更新的问题
        money += refund_amount

        print(f"✅ 退货成功！退还 {refund_amount:.2f}元")
        print(f"💰 您的余额: {money:.2f}元")
        return True

    except ValueError:
        print("❌ 请输入有效的数字！")
        return False


def apply_voucher_at_checkout():
    """结账时应用抵用券"""
    global money, user_coupon

    if user_coupon and user_coupon['type'] == 'voucher':
        voucher_amount = user_coupon['amount']
        total_before_voucher = sum(item['total'] for item in shopping_cart)

        if total_before_voucher >= voucher_amount:
            # 应用抵用券
            discount_amount = voucher_amount
            print(f"🎫 使用抵用券减免: {discount_amount:.2f}元")
            return discount_amount

    return 0


def print_receipt():
    """打印购物小票"""
    global money  # 添加全局声明

    if not shopping_cart:
        print("❌ 购物车为空！")
        return

    # 计算总计
    subtotal = sum(item['total'] for item in shopping_cart)
    total_quantity = sum(item['quantity'] for item in shopping_cart)

    # 应用抵用券
    voucher_discount = apply_voucher_at_checkout()
    final_total = max(0, subtotal - voucher_discount)

    # 如果使用了抵用券，需要更新余额
    if voucher_discount > 0:
        money += voucher_discount  # 抵用券相当于退款

    print("\n" + "=" * 50)
    print("                  购物小票")
    print("=" * 50)
    print(f"购物时间: {datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
    print("-" * 50)

    # 商品明细
    print("商品名称    数量    单价      小计")
    print("-" * 50)
    for item in shopping_cart:
        price_display = f"{item['final_price']:.1f}元"
        if item['final_price'] < item['price']:
            price_display += f"*"

        print(f"{item['name']:8} x{item['quantity']:2}   {price_display:8}  {item['total']:6.1f}元")

    print("-" * 50)

    # 优惠信息
    total_savings = sum(item['original_total'] - item['total'] for item in shopping_cart)
    if total_savings > 0:
        print(f"商品优惠:               -{total_savings:.1f}元")

    if voucher_discount > 0:
        print(f"抵用券优惠:             -{voucher_discount:.1f}元")

    print("-" * 50)
    print(f"商品数量: {total_quantity}件")
    print(f"商品总价: {subtotal:.1f}元")
    print(f"实付金额: {final_total:.1f}元")
    print(f"卡余额:   {money:.1f}元")
    print("=" * 50)

    if total_savings > 0 or voucher_discount > 0:
        print(f"💰 本次购物共节省: {total_savings + voucher_discount:.1f}元")

    print("          谢谢光临！欢迎下次再来！")
    print("=" * 50)


def shopping_process():
    """购物主流程"""
    global money

    print("🎉=== 欢迎来到超市购物系统 ===")
    print(f"💰 您的初始余额: {money:.2f}元")

    # 抽取优惠券
    draw_coupon()

    while True:
        display_products()

        print(f"\n💰 当前余额: {money:.2f}元")
        if user_coupon:
            print(f"🎫 持有优惠券: {user_coupon['description']}")

        # 用户输入
        print("\n请选择操作:")
        print("1. 购买商品")
        print("2. 退货")
        print("3. 结账退出")

        choice = input("请输入选择 (1-3): ").strip()

        if choice == '1':
            # 购买商品
            product_input = input("请输入商品ID: ").strip()
            try:
                product_id = int(product_input)
            except ValueError:
                print("❌ 请输入有效的商品ID！")
                continue

            product = find_product(product_id)
            if not product:
                print("❌ 没有这个商品！")
                continue

            try:
                quantity = int(input(f"请输入购买数量 (当前库存: {product['stock']}): "))
                if quantity <= 0:
                    print("❌ 数量必须大于0！")
                    continue
            except ValueError:
                print("❌ 请输入有效数量！")
                continue

            add_to_cart(product, quantity)

        elif choice == '2':
            # 退货
            return_product()

        elif choice == '3':
            # 结账退出
            print_receipt()
            break

        else:
            print("❌ 无效的选择，请输入1-3！")


# 运行程序
if __name__ == "__main__":
    shopping_process()